// Package routers
// @Author: zhangdi
// @File: auth
// @Version: 1.0.0
// @Date: 2023/8/28 17:13
package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"server/application/constant/enums"
	"server/pkg/ginp"
	"server/pkg/myjwt"
	"strings"
)

// AuthorizationCheck 进行鉴权
func AuthorizationCheck(c *ginp.ContextPro) {
	//判断该路由是否需要鉴权
	requestApi := c.Request.URL.Path
	for _, router := range Routers {
		if IsPathMatch(router.Path, requestApi) {
			if !router.NeedLogin { //不需要鉴权
				c.Next()
				return
			}

		}
	}

	//需要鉴权
	// 从请求头中获取Token信息
	signToken := c.Request.Header.Get("Authorization")
	signToken = strings.TrimPrefix(signToken, "Bearer ")

	if signToken == "" {
		signToken = c.Param("AuthorizationCheck")
	}
	errInfo := gin.H{
		"code": enums.RespCodeNoLogin,
		"msg":  "鉴权失败，请先登录",
		"data": nil,
	}
	// 解析并验证Token有效性，当校验失败时，响应客户端，并终止后面的处理
	myClaims, err := myjwt.ParserToken(signToken)
	if err != nil {

		c.JSON(http.StatusUnauthorized, errInfo)
		c.Abort()
		return
	}
	// 将用户的ID存放到上下文Context中，后续的处理函数中可以通过c.Get("userid")获取当前请求的ID
	c.Set("userid", myClaims.Id)

	c.Next()

}

// IsPathMatch 判断路由（含有变量）和真实url是否匹配，如果匹配则返回
// route := "/user/:id/:name"    path := "/user/1/sassa" ==>true
func IsPathMatch(route string, path string) bool {
	routeParts := strings.Split(route, "/")
	pathParts := strings.Split(path, "/")

	if len(routeParts) != len(pathParts) {
		return false
	}

	for i, routePart := range routeParts {
		if strings.HasPrefix(routePart, ":") {
			continue
		}
		if strings.HasPrefix(routePart, "*any") {
			continue
		}

		if routePart != pathParts[i] {
			return false
		}
	}

	return true
}
